import { login } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { decryptByAES } from '@/utils/aes'

const user = {
  state: {
    token: getToken(),
    name: '',
    userId: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(response => {
          const data = JSON.parse(decryptByAES(response.data))
          console.log(data)
          setToken('dlb ' + data.token)
          commit('SET_TOKEN', 'dlb ' + data.token)
          commit('SET_NAME', data.loginName)
          commit('SET_USERID', data.id)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
